[Java] Huffman Coding實作壓縮軟體

目前還只是個半成品,Huffman Coding有做出來,但目前只有純文字檔可以正確壓縮,具體原因還有待研究。

最麻煩的地方在於要存成二進位檔,否則檔案越壓縮越大,以及表頭檔該怎麼存,否則該怎麼解碼都不知道。

Compress.jar

Main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Main {
public static void main(String[] args) {
JFrame Frame = new JFrame();
Frame.setSize(300,300);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setVisible(true);
Frame.setLayout(null);
JButton Button_Compress = new JButton("壓縮");
JButton Button_Decompress = new JButton("解壓");
Button_Compress.setSize(60,25);
Button_Decompress.setSize(60,25);
Button_Compress.setLocation(50, 115);
Button_Decompress.setLocation(170, 115);
JPanel Panel = new JPanel();
Panel.setLayout(null);
Panel.setSize(300,300);
Panel.add(Button_Compress);
Panel.add(Button_Decompress);
Frame.add(Panel);
Button_Compress.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
Frame.remove(Panel);
Compress compress = new Compress();
Frame.add(compress);
Frame.repaint();
}
});
Button_Decompress.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
Frame.remove(Panel);
Decompress decompress = new Decompress();
Frame.add(decompress);
Frame.repaint();
}
});
}
}

Compress

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
public class Compress extends JPanel{
String DataName ;
Compress(){
this.setSize(300,300);
this.setLayout(null);
JButton Button_Choose = new JButton("選擇");
JButton Button_Compress = new JButton("壓縮");
JTextField DataSite = new JTextField();
Button_Choose.setSize(60,25);
Button_Compress.setSize(60,25);
DataSite.setSize(200,25);
Button_Choose.setLocation(215, 100);
Button_Compress.setLocation(110, 135);
DataSite.setLocation(10, 100);
DataSite.setText("請選擇檔案");
this.add(Button_Choose);
this.add(Button_Compress);
this.add(DataSite);
HashMap <String, Integer> AppearTimes = new HashMap <String, Integer>();
Button_Choose.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
JFileChooser FileChooser =new JFileChooser();
int ret = FileChooser.showOpenDialog(null);
if( ret == JFileChooser.APPROVE_OPTION)
{
DataName = FileChooser.getSelectedFile().getName() ;
DataSite.setText(FileChooser.getCurrentDirectory()+"\\"+FileChooser.getSelectedFile().getName());
}
} catch (Exception e2){
JOptionPane.showMessageDialog(null,"Error","Error",JOptionPane.ERROR_MESSAGE);
}
}
});
Button_Compress.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
FileReader fr;
try {
fr = new FileReader(DataSite.getText());
BufferedReader br = new BufferedReader(fr);
JOptionPane.showMessageDialog(null,"開始壓縮檔案!");
while (br.ready())
{
String InputLine = br.readLine();
for ( int i = 0 ; i < InputLine.length() ; i ++ )
{
try
{
AppearTimes.put(""+InputLine.charAt(i),AppearTimes.get(InputLine.charAt(i))+1) ;
} catch ( NullPointerException e2 )
{
AppearTimes.put(""+InputLine.charAt(i),1) ;
}
}
try
{
AppearTimes.put("\\r\\n",AppearTimes.get("\r\n")+1) ;
} catch ( NullPointerException e2 )
{
AppearTimes.put("\\r\\n",1) ;
}
}
fr.close();
Vector <Node> v = new Vector();
Iterator iter = AppearTimes.entrySet().iterator();
Node n , m , CombineNode ;
while (iter.hasNext())
{
HashMap.Entry entry = (HashMap.Entry) iter.next();
n = new Node();
n.key = (String) entry.getKey();
n.value = (int) entry.getValue();
v.add(n);
}
PriorityQueue PQ = new PriorityQueue();
PQ.insert(v);
while( PQ.heap.size() > 1 )
{
n = PQ.remove() ;
m = PQ.remove() ;
CombineNode = new Node();
CombineNode.key = null ;
CombineNode.value = n.value + m.value ;
CombineNode.left = n ;
CombineNode.right = m ;
v.clear();
v.add(CombineNode) ;
PQ.insert(v);
}
Node TreeNode = PQ.remove() ;
HashMap <String, String> HuffmanCode = new HashMap <String, String>();
if ( TreeNode.left == null && TreeNode.right == null )
{
TreeNode.code = "0" ;
}
else
{
Queue <Node> q = new LinkedList();
q.offer(TreeNode);
while (!q.isEmpty())
{
Node p = q.poll();
if ( p.key != null)
HuffmanCode.put(p.key,p.code) ;
if (!(p.left == null) )
{
q.offer(p.left);
p.left.code = p.code + "0" ;
}
if (!(p.right == null))
{
q.offer(p.right);
p.right.code = p.code + "1" ;
}
}
}
FileWriter fw = new FileWriter("C_"+DataName);
fr = new FileReader(DataSite.getText());
br = new BufferedReader(fr);
iter = HuffmanCode.entrySet().iterator();
while (iter.hasNext())
{
HashMap.Entry entry = (HashMap.Entry) iter.next();
String c = (String) entry.getKey() ;
String s = (String) entry.getValue() ;
for ( int k = 0 ; k < c.length() ; k ++ )
{
int ni = (int)c.charAt(k);
String ns = Integer.toBinaryString(ni) ;
fw.write(ns);
}
fw.write(Integer.toBinaryString(32)) ;
fw.write(s);
fw.write(Integer.toBinaryString(32)) ;
}
fw.write(HuffmanCode.get("\\r\\n"));
while (br.ready())
{
String InputLine = br.readLine();
for ( int i = 0 ; i < InputLine.length() ; i ++ )
{
fw.write(HuffmanCode.get(""+InputLine.charAt(i)));
}
fw.write(HuffmanCode.get("\\r\\n"));
}
fw.flush();
fw.close();
BufferedOutputStream fw2 = new BufferedOutputStream(new FileOutputStream("C_"+DataName+".cpr"));
//fw = new FileWriter("C2_"+DataName);
fr = new FileReader("C_"+DataName);
br = new BufferedReader(fr);
int time = 0 ;
while (br.ready())
{
String InputLine = br.readLine();
InputLine += HuffmanCode.get("\\r\\n");
if ( InputLine.length() % 7 != 0 )
{
for ( int i = InputLine.length() % 7 ; i < 8 ; i ++ )
InputLine += "0" ;
}
byte[] buf = new byte[InputLine.length() / 7];
for(int i = 0; i * 7 + 7 <= InputLine.length(); i ++)
buf[i] = Byte.valueOf(InputLine.substring(i * 7, i * 7 + 7), 2);
fw2.write(buf);
}
iter = HuffmanCode.entrySet().iterator();
while (iter.hasNext())
{
HashMap.Entry entry = (HashMap.Entry) iter.next();
System.out.println(entry.getKey()+" "+entry.getValue() ) ;
}
fw2.flush();
fw2.close();
JOptionPane.showMessageDialog(null,"壓縮完成!");
} catch (IOException e1) {
JOptionPane.showMessageDialog(null,"Error","Error",JOptionPane.ERROR_MESSAGE);
}
}
});
}

Decompress

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
public class Decompress extends JPanel{
String DataName ;
BinaryCode BC = new BinaryCode();
Decompress(){
this.setSize(300,300);
this.setLayout(null);
JButton Button_Choose = new JButton("選擇");
JButton Button_Compress = new JButton("解壓");
JTextField DataSite = new JTextField();
Button_Choose.setSize(60,25);
Button_Compress.setSize(60,25);
DataSite.setSize(200,25);
Button_Choose.setLocation(215, 100);
Button_Compress.setLocation(110, 135);
DataSite.setLocation(10, 100);
DataSite.setText("請選擇檔案");
this.add(Button_Choose);
this.add(Button_Compress);
this.add(DataSite);
HashMap <Character, Integer> AppearTimes = new HashMap <Character, Integer>();
Button_Choose.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
JFileChooser FileChooser =new JFileChooser();
int ret = FileChooser.showOpenDialog(null);
if( ret == JFileChooser.APPROVE_OPTION)
{
DataName = FileChooser.getSelectedFile().getName() ;
DataSite.setText(FileChooser.getCurrentDirectory()+"\\"+FileChooser.getSelectedFile().getName());
}
} catch (Exception e2){
JOptionPane.showMessageDialog(null,"Error","Error",JOptionPane.ERROR_MESSAGE);
}
}
});
HashMap <String, String> DecodeMap = new HashMap <String, String>();
/*
DecodeMap.put("11", '1');
DecodeMap.put("00", '2');
DecodeMap.put("010", '3');
DecodeMap.put("0110", '4');
DecodeMap.put("0111", '5');
DecodeMap.put("10", '6');
*/
Button_Compress.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try {
FileWriter fw = new FileWriter("O_"+DataName);
BufferedInputStream fr = new BufferedInputStream(new FileInputStream(DataSite.getText()));
StringBuffer resultStr = new StringBuffer();
StringBuffer codeStr = new StringBuffer();
byte[] buf = new byte[1];
JOptionPane.showMessageDialog(null,"開始解壓縮檔案!");
int LineNumber = 0 ;
while(fr.read(buf) != -1)
{
String bStr = Integer.toBinaryString(buf[0]);
StringBuffer temp = new StringBuffer();
for(int j = 0; j < 7 - bStr.length(); j ++)
temp.append('0');
codeStr.append(temp + bStr);
}
String InputLine = codeStr.toString() ;
int site = 0 ;
boolean b_key = false ;
boolean b_value = true ;
String key = "" ;
String value = "" ;
String s = "" ;
for ( int i = 0 ; i < InputLine.length() ; i ++ )
{
s += InputLine.charAt(i) ;
if ( InputLine.charAt(i+1) == '1' && InputLine.charAt(i+2) == '0' && InputLine.charAt(i+3) == '0' &&
InputLine.charAt(i+4) == '0' && InputLine.charAt(i+5) == '0' && InputLine.charAt(i+6) == '0')
{
if ( b_key == true )
{
b_value = true ;
b_key = false ;
key = s ;
if ( value.equals("1011100111001010111001101110") )
{
DecodeMap.put(key, "\\r\\n" ) ;
s = "" ;
}
else
{
int n = Integer.valueOf(BC.BinaryToDecimal(value));
char c = (char)n ;
DecodeMap.put(key, "" + c );
s = "" ;
}
}
else if ( b_value == true )
{
b_key = true ;
b_value = false ;
value = s ;
s = "" ;
}
i += 6 ;
}
if ( DecodeMap.get(s) == "\\r\\n" )
{
System.out.println(s);
site = i + 1 ;
break ;
}
}
InputLine = InputLine.substring(site, InputLine.length()) ;
for (int i = 0 ; i < InputLine.length() ; i ++ )
{
s = "" ;
for ( int j = i ; j < InputLine.length() ; j ++ )
{
s += InputLine.charAt(j) ;
if ( DecodeMap.containsKey(s))
{
if ( DecodeMap.get(s) == "\\r\\n" )
{
fw.write("\r\n") ;
i = j ;
}
else
{
fw.write(DecodeMap.get(s));
i = j ;
}
break ;
}
}
}
fr.close();
fw.flush();
fw.close();
Iterator iter = DecodeMap.entrySet().iterator();
while (iter.hasNext())
{
HashMap.Entry entry = (HashMap.Entry) iter.next();
System.out.println(entry.getKey()+" "+entry.getValue() ) ;
}
JOptionPane.showMessageDialog(null,"解壓縮完成!");
} catch (IOException e1) {
JOptionPane.showMessageDialog(null,"Error","Error",JOptionPane.ERROR_MESSAGE);
}
}
});
}
}

Node

1
2
3
4
5
6
7
public class Node {
public String key = null;
public int value = 0 ;
public Node left = null ;
public Node right = null ;
public String code = "" ;
}

Priority Queue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
public class PriorityQueue {
Vector<Node> heap = new Vector();
public void insert(Vector<Node> v)
{
for ( int i = 0 ; i < v.size() ; i ++ )
{
heap.add(v.get(i)) ;
}
for ( int i = heap.size()-v.size() ; i < heap.size() ; i ++ )
{
for( int j = i ; j > 0 ; j /= 2 )
{
int k ;
if ( j % 2 == 0 )
{
k = j / 2 - 1 ;
}
else
{
k = j / 2 ;
}
if ( heap.get(j).value < heap.get(k).value )
{
Node temp = heap.get(j) ;
heap.set(j,heap.get(k)) ;
heap.set(k,temp) ;
}
else
{
break ;
}
}
}
}
public Node remove()
{
Node n = heap.get(0) ;
heap.set(0,heap.get(heap.size()-1)) ;
heap.set(heap.size()-1,n) ;
for( int i = 0 ; i < heap.size() ; )
{
int k = i * 2 + 1 ;
if ( heap.size() - 1 <= k )
{
break ;
}
else if ((heap.get(i).value < heap.get(k).value && heap.get(i).value < heap.get(k+1).value ) )
{
break ;
}
else if (heap.size() - 1 <= k + 1 )
{
Node temp = heap.get(i) ;
heap.set(i,heap.get(k)) ;
heap.set(k,temp) ;
i = i * 2 + 1 ;
}
else if ( heap.get(k).value < heap.get(k+1).value )
{
Node temp = heap.get(i) ;
heap.set(i,heap.get(k)) ;
heap.set(k,temp) ;
i = i * 2 + 1 ;
}
else
{
Node temp = heap.get(i) ;
heap.set(i,heap.get(k+1)) ;
heap.set(k+1,temp) ;
i = i * 2 + 2 ;
}
}
heap.remove(heap.size()-1) ;
return n ;
}
PriorityQueue(){
heap.clear();
}
}

BinaryCode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class BinaryCode {
public static String BinaryToDecimal(String x){
long n = Long.valueOf(x) ;
int sum = 0 ;
int level = 1 ;
while( n > 0 )
{
sum += ( n % 10 ) * level ;
level *= 2 ;
n /= 10 ;
}
String s = String.valueOf(sum) ;
return s ;
}
public static String DecimalToBinary(String x){
int n = Integer.valueOf(x) ;
int[] sum ;
sum = new int[100] ;
int count = 0 ;
while( n > 0 )
{
sum[count] = n % 2 ;
n /= 2 ;
count ++ ;
}
long sum2 = 0 ;
long level = 1 ;
int i = 0 ;
while( i < count )
{
sum2 += sum[i] * level ;
i ++ ;
level *= 10 ;
}
String s = String.valueOf(sum2) ;
return s ;
}
BinaryCode(){
}
}